import { authStatusApi } from '@/api/Auth';
import { defineStore } from 'pinia'

export const useGlobalStore = defineStore<string, {
    appQr : {
        show : boolean;
        src : string;
    },
    loginStatus : boolean, accessToken : string; accessExpireIn : number; role:string,unreadMsgCount : number,
    userInfo : {
        name:string;
        gh:string;
        xh:string;
        class:string;
        grade:string;
        jobPost:string;
        avatar:string;
        dept:string;
        sex:1|2

    }},{},
    {
        setCache : (data:any) => void,
        init: () => void;
        logout : () => void,
        login : () => void
    }
    >('global', {
    state() {
        return {
            unreadMsgCount : 0,
            accessToken : '',
            accessExpireIn : 0,
            loginStatus : false,
            role : '',
            userInfo : {
                name : '',
                gh : '',
                xh : '',
                class : '',
                grade : '',
                jobPost : '',
                avatar:'',
                dept:'',
                sex:1,
            },

            appQr : {
                show : false,
                src : ''
            }
        }
    },

    actions : {
        setCache(data) {
            localStorage.setItem("user", JSON.stringify(data))
        },

        async init() {
            const status = sessionStorage.getItem("authStatus")
            const cache = localStorage.getItem("user")
            if(status && cache) {
                const data = JSON.parse(cache)
                this.loginStatus = true
                this.role = data.role
                this.userInfo = data.userInfo
            }else {
                const r = await authStatusApi()
                if(r.success) {
                    sessionStorage.setItem("authStatus", '1')
                    const data = r.data
                    this.role = data.role
                    this.userInfo = data.userInfo
                    this.loginStatus = true
                }
            }
            
        },
        
        login() {
            location.href = import.meta.env.B_APIURL + "auth/auth"
        },

        logout() {
            sessionStorage.removeItem('authStatus')
            localStorage.removeItem("user")
            this.loginStatus = false
            this.accessToken = ''

            location.href = import.meta.env.B_APIURL + "auth/logout"
        }
    }
})